import React, {PureComponent} from 'react';
import {
    Input,
    Button,
    Icon,
    Row,
    Col,
    Table,
    Form
} from 'antd';
const FormItem = Form.Item;

function get2dArr(arr) {
    /*
     * 格式化数组为 [[1,2],[3,4],[5,6]...]
     * */
    if (!Array.isArray(arr)) {
        console.error('arr 参数必须为array');
        return false;
    }
    let tempArr = [];
    arr.forEach((v, i)=> {
        tempArr.push([]);
        v.specvs.forEach(val=> {
            tempArr[i].push(val.name);
        });
    });
    return tempArr;
}

function split2MultiArr(arr = []) {
    /*
     * @params
     * arr = [[1,2],[3,4],[5,6]...];
     * return
     *  [[1,3,5],[1,3,6],[2,3,5]...]
     * */
    function getTemp(arr1, arr2) {
        let temp = [];
        arr1.forEach((v, i)=> {
            arr2.forEach((val, j)=> {
                if (Array.isArray(v)) {
                    temp.push([
                        ...v,
                        val
                    ]);
                } else {
                    temp.push([
                        v,
                        val
                    ]);
                }
            })
        });
        return temp;
    }

    let temp = [];

    if (arr.length == 0) {
        return [];
    } else if (arr.length == 1) {
        if (Array.isArray(arr[0])) {  //确保是个二维数组
            arr[0].forEach((v, i)=> {
                temp[i] = [v];
            });
        } else {
            return arr;
        }
    }

    for (let i = 1; i < arr.length; i++) {
        if (temp.length > 0) {
            temp = getTemp(temp, arr[i]);
        } else {
            temp = getTemp(arr[i - 1], arr[i]);
        }
    }
    ;

    return temp;
}


export default class SpecList extends PureComponent {
    state = {
        batchType: '', //批量设置类型
        inputValue: '',
        listData: [{price: '', stock: '', settlement_price: ''}],  //用于保存价格和库存
    };

    bindChangeType = (type)=> {
        this.setState({
            batchType: type
        });
    };

    bindInputChange = (e)=> {
        this.setState({
            inputValue: e.target.value
        });
    };

    bindTypeValue = ()=> {
        const {batchType, inputValue, listData} = this.state;
        const {data} = this.props;
        const len = split2MultiArr(get2dArr(data)).length;

        let result = [...listData];
        for (var i = 0; i < len; i++) {
            if (!result[i]) {
                result[i] = {price: '', stock: '', settlement_price: ''};
            }
            result[i][batchType] = inputValue;
        }
        console.log(result);
        this.setState({
            listData: result,
            batchType: '',  //隐藏
            inputValue: '',
        });
    };

    bindChangePriceStock = (e, index, type)=> {
        const {listData} = this.state;
        let result = [...listData];
        if (!result[index]) {
            result[index] = {}
        }
        result[index][type] = e.target.value;
        this.setState({
            listData: result
        });
    };

    componentWillReceiveProps = (props)=> {
        let stateListData = this.state.listData;
        if (props.specList.length > 0 && stateListData.length == 1 && stateListData[0].price == '' && stateListData[0].stock == '') {  //只有修改初始时需要设置该值
            const listData = props.specList.map(v=> {
                return {
                    id: v.id, //sku id用于生成小程序二维码
                    price: v.price,
                    stock: v.stock,
                    settlement_price: v.settlement_price
                }
            });
            this.setState({
                listData,
            });
        }
    };

    bindCreateQc = (id)=> {
        //生成小程序二维码
        this.props.dispatch({
            type: 'addGoods/createQrcode',
            payload: {
                app_type: 'SmallApp',
                scene: id,
                //page : "pages/shop/suborder/suborder",
                page: "pages/detail/detail"
            }
        }).then(url=> {
            console.log(url);
        })
    };

    render() {
        const {batchType, inputValue, listData} = this.state;
        const {data, onChange} = this.props;
        console.log('data', JSON.stringify(data));
        console.log('listData', JSON.stringify(listData));
        // let columnsData = [{
        //   0 : 1,
        //   1 : 2,
        //   2 : 3,
        //   price : 10,
        //   stock: 10,
        // }];

        let columnsData = [];
        const tempArr = split2MultiArr(get2dArr(data));

        console.log('tempArr', tempArr);
        tempArr.forEach((v, i)=> {
            if (v != '') {
                let item = {key: i};
                v.forEach((val, j)=> {
                    item[j] = val;
                    item.key = item.key + val;
                });
                item.price = listData[i] && listData[i].price ? listData[i].price : '';
                item.stock = listData[i] && listData[i].stock ? listData[i].stock : '';
                item.settlement_price = listData[i] && listData[i].settlement_price ? listData[i].settlement_price : '';
                //item.id = listData[i].id || '';
                columnsData.push(item);
            }
        });

        console.log('columnsData', columnsData);
        onChange(columnsData);

        let tempColumns = [];
        if (Array.isArray(data)) {
            data.forEach((v, i)=> {
                if (v.name != '') {
                    tempColumns.push({
                        title: v.name,
                        dataIndex: i,
                        key: v.key
                    })
                }
            });
        } else {
            console.error('data 不为 Array', data);
        }

        const columns = [
            ...tempColumns,
            {
                title: '价格',
                dataIndex: 'price',
                key: 'price',
                render: (text, record, index) => (<Input value={record.price} onChange={(e)=> {
                    this.bindChangePriceStock(e, index, 'price')
                }} style={{width: '100px'}}/>)
            }, {
                title: '库存',
                dataIndex: 'stock',
                key: 'stock',
                render: (text, record, index) => (<Input value={record.stock} onChange={(e)=> {
                    this.bindChangePriceStock(e, index, 'stock')
                }} style={{width: '100px'}}/>)
            }, {
                title:'供货价',
                key: 'settlement_price',
                render: (text, record, index) => (<Input value={record.settlement_price} onChange={(e)=> {
                    this.bindChangePriceStock(e, index, 'settlement_price')
                }} style={{width: '100px'}}/>)
            }
            /*,
             {
             title : '操作',
             key : 'id',
             render : (text, record)=>{
             return record.id ? <a href="javascript:;" onClick={()=>{this.bindCreateQc(record.id)}}>生成小程序二维码</a> : null;
             }
             }*/
        ];

        return <div>
            <Table rowKey="key" bordered dataSource={columnsData} columns={columns} pagination={false}></Table>
            <Row gutter={8}>
                <Col span={3}><a onClick={()=> {
                    this.bindChangeType('price')
                }}><Icon type="edit"/> 批量设置价格</a></Col>
                <Col span={3}><a onClick={()=> {
                    this.bindChangeType('stock')
                }}><Icon type="edit"/> 批量设置库存</a></Col>
                <Col span={3}><a onClick={()=> {
                    this.bindChangeType('settlement_price')
                }}><Icon type="edit"/> 批量设置供货价</a></Col>
                <div style={{display: batchType != '' ? 'block' : 'none'}}>
                    <Col span={8}><Input style={{width: '97%'}}
                                         placeholder={batchType == 'price' ? '请输入批量价格' : batchType == 'stock' ? '请输入批量库存' : '请输入批量供货价'} value={inputValue}
                                         onChange={this.bindInputChange}/></Col>
                    <Col span={4}><Button onClick={this.bindTypeValue}>设置</Button></Col>
                    <Col span={3}><Button onClick={()=> {
                        this.bindChangeType('')
                    }}>取消</Button></Col>
                </div>
            </Row>
        </div>
    }
}
